package com.bookbuf.app;

import android.app.LoaderManager;
import android.content.Context;
import android.content.Intent;
import android.content.Loader;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

import com.bookbuf.library.LoaderLayout;
import com.bookbuf.library.LoaderResult;
import com.bookbuf.library.adapter.impl.LoaderResultAdapter;
import com.bookbuf.library.loader.GenericAsyncLoader;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class DataRequestActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<LoaderResult<List<Integer>>> {

	LoaderLayout loaderLayout;
	LoaderResultAdapter adapter;

	public static void callMe (Context context) {
		context.startActivity (new Intent (context, DataRequestActivity.class));
	}

	@Override
	protected void onCreate (Bundle savedInstanceState) {
		super.onCreate (savedInstanceState);
		setContentView (R.layout.activity_data_request);

		adapter = new LoaderResultAdapter ();

		loaderLayout = (LoaderLayout) findViewById (R.id.loading_layout);
		loaderLayout.setInteractionListener (new LoaderLayout.InteractionListener () {

			@Override
			public void onInflateContentView (View view, LoaderResult<?> result) {

				List<Integer> list = (List<Integer>) result.getData ();

				TextView tv = (TextView) view.findViewById (R.id.tvXXX);

				StringBuilder builder = new StringBuilder ();
				for (Integer number : list) {
					builder.append (number);
					builder.append (",");
				}
				tv.setText (builder.toString ());
			}

			@Override
			public void onEventRetry () {
				getLoaderManager ().restartLoader (1000, null, DataRequestActivity.this);
			}


		});
		loaderLayout.setAdapter (adapter);
		getLoaderManager ().initLoader (1000, null, this);
	}

	@Override
	public Loader<LoaderResult<List<Integer>>> onCreateLoader (int id, final Bundle args) {

		// don't ignore setLoading().
		adapter.setLoading ();

		GenericAsyncLoader<List<Integer>> loader = new GenericAsyncLoader<> (DataRequestActivity.this);
		loader.setRequest (new GenericAsyncLoader.Request<List<Integer>> () {
			@Override
			public LoaderResult<List<Integer>> run () {

				// XXX Mock api request.
				try {
					Thread.sleep (1000);
				} catch (InterruptedException e) {
					e.printStackTrace ();
				}
				List<Integer> list = new ArrayList<> ();
				for (int i = 0; i < 10; i++) {
					list.add (new Random ().nextInt ());
				}
				LoaderResult<List<Integer>> result = new LoaderResult<> ();
				result.setSuccess (true);
				result.setData (list);
				return result;
			}
		});
		return loader;
	}

	@Override
	public void onLoadFinished (Loader<LoaderResult<List<Integer>>> loader, LoaderResult<List<Integer>> result) {
		adapter.setResult (result);
	}

	@Override
	public void onLoaderReset (Loader<LoaderResult<List<Integer>>> loader) {
		// ignore ...
	}
}
